<template>
  <el-dialog
    :destroy-on-close="true"
    :visible="isShow"
    @close="closeModal"
  >
    <el-form
      ref="saveForm"
      :model="saveFormData"
      label-suffix=":"
      label-width="100px"
      :rules="rules"
      @submit.native.prevent="saveConfig"
    >
      <el-form-item label="名称" prop="name">
        <el-input v-model="saveFormData.name" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :loading="loading" @click="saveConfig">保存</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { SaveFormConfig, CreateFormTable } from '@/api/formManagement';
import { EnumComponentType } from '@/constants/app/EnumDashboard';
export default {
  name: 'SaveFormConfig',
  props: {
    isShow: {
      type: Boolean,
      required: true,
      default() {
        return false;
      }
    },
    formConfig: {
      type: Object,
      required: true,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      loading: false,
      saveFormData: {
        name: ''
      },
      rules: {
        name: { required: true, whitespace: true, message: '请输入名称' }
      }
    };
  },
  methods: {
    saveConfig() {
      const { saveFormData, formConfig } = this;
      this.loading = true;
      this.$refs.saveForm.validate((valid, field) => {
        if (valid) {
          SaveFormConfig(saveFormData.name, formConfig).then(res => {
            const formId = res.data;
            const tableParams = this.formatterField(formConfig.list);
            return CreateFormTable({ formId, columns: tableParams });
          }, err => {
            this.$message.error(err.msg);
            this.loading = false;
          }).then(res => {
            this.loading = false;
            this.$message.success(res.msg);
            this.$emit('clearEditor');
            this.closeModal();
          }, err => {
            this.$message.error(err.msg);
            this.loading = false;
          });
        } else {
          this.$message.warning('请输入名称');
        }
      });
    },
    /* 格式化建表参数*/
    formatterField(fieldList = []) {
      const tableParams = [];
      fieldList.forEach(item => {
        if (item.type === EnumComponentType.grid) {
          const gridItemList = this.formatterGridField(item.columns);
          tableParams.push(...gridItemList);
        } else {
          tableParams.push({ name: item.model, type: 'varchar(20)' });
        }
      });
      return tableParams;
    },

    /* 格式化grid内建表参数*/
    formatterGridField(gridColumns = []) {
      const fieldList = [];
      gridColumns.forEach(gridItem => {
        gridItem.list.forEach(componentItem => {
          fieldList.push({ name: componentItem.model, type: 'varchar(20)' });
        });
      });
      return fieldList;
    },

    closeModal() {
      this.$emit('update:isShow', false);
    }
  }
};
</script>

<style scoped>

</style>
